<template>
  <!-- 知识类型管理 -->
  <div class="knowledgeType">
    <ContentWrap>
      <FormContainer :column="3">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="100px">
          <el-form-item prop="typeCode" label="知识类型编号">
            <el-input v-model="formData.typeCode" placeholder="请输入类型编号" clearable />
          </el-form-item>
          <el-form-item prop="id" label="知识类型名称">
            <SearchSelectPicker
              url="/call-center/api/v1/knowledgeType/page"
              placeholder="请选择类型名称"
              :params="{query:{type: 'needAuditor'},type:0}"
              lable-name="typeName"
              :value.sync="formData.id"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item prop="isAuditRequired" label="是否需要审核">
            <el-select v-model="formData.isAuditRequired" clearable filterable>
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item prop="createBy" label="创建人">
            <StaffSearch v-model="formData.createBy" placeholder="请输入创建人" clearable />
          </el-form-item>
          <el-form-item prop="createTime" label="创建时间">
            <el-date-picker
              v-model="formData.createTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              opt
              operator=">"
              :limite="new Date()"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <Button @click="$refs.form.resetFields()">重置</Button>
            <Button type="primary" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <div class="button-container" style="padding-top:0">
        <Button type="primary" @click="add">新增</Button>
        <Button type="primary" @click="update">编辑</Button>
        <Button type="danger" @click="delet">删除</Button>
        <Button type="primary" @click="toExamine">审核</Button>
      </div>
      <table-box
        ref="table"
        no-request
        :table-config="tableConfig"
        :other-filters="typeManageParams"
        @row-click="rowSelect"
      >
        <!-- <el-table-column slot="before" align="center" type="selection" width="50"></el-table-column> -->
      </table-box>
      <AddEdit ref="addEdit" :cur-data="tempData" :auditor-name="AuditorOption" :dailog-type="dailogType" @requestSinga="requestSinga('onPage')" />
      <Examine ref="examine" :cur-data="tempData" @requestSinga="requestSinga('onPage')" />
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import FormContainer from '@/components/FormContainer'
import Button from '@/components/Button'
import AddEdit from './child/AddEdit'
import Examine from './child/Examine'
import StaffSearch from '@/components/StaffSearch'
import { deleteKonwledgeType } from '@/api/knowledgeType'
import { filtersRaw, addOneDay } from '@/utils'
import SearchSelectPicker from '@/components/SearchSelectPicker'
export default {
  name: 'KnowledgeTypeManage',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    AddEdit,
    Examine,
    SearchSelectPicker,
    StaffSearch
  },
  data() {
    return {
      AuditorOption: [],
      dailogType: 0,
      formData: {
        typeCode: '',
        id: '',
        type: 'needAuditor',
        isAuditRequired: '',
        createBy: '',
        createTime: []
      },
      tempData: {
        id: '',
        typeLable: '',
        role: '',
        examine: '',
        examinePeople: '',
        remarks: ''
      },
      formRules: {},
      typeManageParams: [],
      tableConfig: {
        interfacePath: '/call-center/api/v1/knowledgeType/page',
        sort: 'lastUpdateTime',
        order: 'desc',
        pageFlag: true,
        hideFuncBar: true,
        // 表格字段动态配置
        setting: [
          {
            prop: 'index',
            label: '序号',
            width: 80,
            align: 'center',
            formatData: function(val) { return val.keyIndex + 1 }
          },
          {
            prop: 'typeCode',
            label: '知识类型编号',
            minWidth: 160
          },
          {
            prop: 'typeName',
            label: '知识类型名称',
            minWidth: 150
          },
          {
            prop: 'remarks',
            minWidth: 150,
            label: '备注'
          },
          {
            prop: 'deptName',
            label: '使用业务组',
            minWidth: 120
          },
          {
            prop: 'createName',
            label: '创建人',
            formatData: function(val) {
              if (val.createName) return `${val.createName}(${val.createBy})`
              return '--'
            },
            minWidth: 120
          },
          {
            prop: '',
            label: '最近更新时间',
            formatData: function(val) {
              if (val.lastUpdateTime) return val.lastUpdateTime.substring(0, 19)
              return '--'
            },
            minWidth: 140
          },
          {
            prop: '',
            label: '最近更新人',
            formatData: function(val) {
              if (val.lastUpdateName) return `${val.lastUpdateName}(${val.lastUpdateBy})`
              return '--'
            },
            minWidth: 120
          },
          {
            prop: 'isAuditRequired',
            label: '是否需要审核',
            align: 'center',
            formatData: function(val) {
              if (val.isAuditRequired === 1) {
                return '是'
              } else {
                return '否'
              }
            },
            minWidth: 120
          },
          {
            prop: 'auditorName',
            label: '审核人',
            formatData: function(val) {
              if (val.auditorName) return `${val.auditorName}(${val.auditor})`
              return '--'
            },
            minWidth: 120
          },
          {
            prop: 'state',
            label: '审核状态',
            align: 'center',
            formatData: function(val) {
              return val.isAuditRequired === 0
                ? ''
                : val.state === 1
                  ? '未审核'
                  : val.state === 2
                    ? '审核通过'
                    : val.state === 3
                      ? '审核不通过'
                      : ''
            },
            minWidth: 120
          },
          {
            prop: 'auditRemarks',
            label: '审核备注',
            minWidth: 120
          },
          {
            prop: 'auditTime',
            label: '审核时间',
            formatData: function(val) {
              if (val.auditTime) return val.auditTime.substring(0, 19)
              return '--'
            },
            minWidth: 140
          },
          {
            prop: 'createTime',
            label: '创建时间',
            formatData: function(val) {
              if (val.createTime) return val.createTime.substring(0, 19)
              return '--'
            },
            minWidth: 140
          }
        ],
        btnList: []
      },
      canControl: false,
      pickerOptions: {
        disabledDate(date) {
          return date > new Date()
        }
      }
    }
  },
  methods: {
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    // 根据条件查询
    queryHandle() {
      this.$refs.form
        .validate()
        .then(() => {
          // FIXME:
          const list = []
          for (const i in this.formData) {
            if (i === 'createTime') {
              if (this.formData[i] && this.formData[i].length) {
                list.push(filtersRaw(i, this.formData[i][0], '>='))
                list.push(filtersRaw(i, addOneDay(this.formData[i][1]), '<='))
              }
            } else {
              if (this.formData[i] || this.formData[i] === 0) {
                if (i === 'id' || i === 'isAuditRequired' || i === 'type' || i === 'createBy') {
                  list.push(filtersRaw(i, this.formData[i], '='))
                } else {
                  list.push(filtersRaw(i, this.formData[i], 'like'))
                }
              }
            }
          }
          this.typeManageParams = list
          this.$nextTick(() => {
            this.requestSinga()
          })
        })
        .finally(() => {

        })
    },
    /**
     * 刷新表格
     */
    requestSinga(type) {
      this.$refs.table.initTableData(type || 'opCondition')
    },
    // 新增按钮
    add() {
      this.dailogType = 0
      this.$refs.addEdit.openDailog()
    },
    /**
     * 点击表格获取当行数据
     */
    rowSelect(row) {
      const params = { ...row.row }
      delete params.keyIndex
      if (params.deptCode) {
        const arr = params.deptCode.split(',')
        const newArr = []
        arr.forEach(item => {
          newArr.push(Number(item))
        })
        params.deptCode = newArr
      }
      if (params.deptName) params.deptName = params.deptName.split(',')
      this.tempData = params
      // 判断是否具有操作权限
      const isAuditRequired = this.tempData.isAuditRequired
      const deptCode = this.tempData.deptCode
      const auditor = this.tempData.auditor
      const createBy = this.tempData.createBy
      let bol = false // 能否操作
      if (isAuditRequired === 1) {
        if (this.$isAccount(createBy) || this.$isAccount(auditor)) {
          bol = true
        }
        // 3.原需审核的知识类型名称，只有创建人和审核人可以修改，新修改后仍需审核，即由审核人审核，
        // 如不需审核，修改后即可发布。 当前登录用户 ?= createBy, auditor
      } else if (isAuditRequired === 0) {
        deptCode.forEach(e => {
          if (this.$inGroup(e)) {
            bol = true
            return
          }
        })
        // 1.原不需要审核的知识类型名称，可使用的角色都可以修改；
        // 2.原不需要审核的知识类型名称，修改后如果还是不需审核即可发布，如需审核，则审核后发布；
        // 当前登录用户 角色是否在 知识库浏览权限中
      }
      this.canControl = bol
    },
    // 修改按钮
    update() {
      if (!this.tempData.id) {
        this.$message({
          message: '请选择需要修改的知识类型',
          type: 'info'
        })
        return
      }
      if (!this.canControl) {
        this.$message({
          message: '您没有权限操作该知识类型',
          type: 'info'
        })
        return
      }
      this.dailogType = 1
      this.$nextTick(() => {
        this.$refs.addEdit.openDailog(this.tempData)
      })
    },
    // 执行删除
    delet() {
      const _this = this
      if (!_this.tempData.id && _this.tempData.id !== undefined && _this.tempData.id !== 'undefined') {
        _this.$message({
          message: '请选择需要删除的知识类型',
          type: 'info'
        })
        return
      }

      if (!this.canControl) {
        this.$message({
          message: '您没有权限删除该知识类型',
          type: 'info'
        })
        return
      }
      return _this.$msgbox({
        title: '提示',
        type: 'warning',
        showCancelButton: true,
        message: '确定删除此知识类型?'
      })
        .then(() => {
          return deleteKonwledgeType(_this.tempData.id)
            .then(res => {
              if (res.success === 1) {
                _this.requestSinga()
                _this.$message({
                  message: '删除成功',
                  type: 'success'
                })
              }
            })
        })
        .catch(e => e)
    },
    // 审核按钮
    toExamine() {
      if (!this.tempData.id) {
        this.$message({
          message: '请选择需要审核的知识类型',
          type: 'info'
        })
        return
      }
      const isAuditRequired = this.tempData.isAuditRequired
      const auditor = this.tempData.auditor
      if (isAuditRequired !== 1) {
        this.$message({
          message: '该知识类型不需要审核',
          type: 'info'
        })
        return
      }
      if (this.tempData.state === 2) {
        return this.$message.info('该知识类型已审核通过')
      }
      if (!this.$isAccount(auditor)) {
        this.$message({
          message: '您没有权限审核该知识类型',
          type: 'info'
        })
        return
      }
      // 3.原需审核的知识类型名称，只有创建人和审核人可以修改，新修改后仍需审核，即由审核人审核，
      // 如不需审核，修改后即可发布。 当前登录用户 ?= auditor
      this.$refs.examine.openDailog(this.tempData)
    }
  }
}
</script>
<style lang='scss' scope>
.knowledgeType .el-form-item--mini .el-form-item__content .inline-input {
  width: 100%;
}
</style>
